
<template>
  <div>
    <SearchForm
        @search="onSearch"
        @reset="onReset"
        :search-list="searchList" :search-params="searchParams">
    </SearchForm>

    <div class="table-layout">
      <el-card shadow="never">
        <div class="table-handle">
          <el-upload
              class="upload-demo"
              action=""
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleChange"
              accept=".xlsx, .xls">
            <el-button type="primary">选择Excel文件</el-button>
          </el-upload>
          <el-button type="primary" style="margin-left: 15px" icon="el-icon-plus" @click="onAdd">新增</el-button>
        </div>
        <div class="table-box">
          <el-table
              size="large"
              stripe
              border
              v-loading="loading"
              max-height="600px"
              :data="tableData"
              row-key="id"
              element-loading-spinner="el-icon-loading"
              element-loading-background="rgba(255, 255, 255, 0.8)"
              @selection-change="onSelect"
            >
              <el-table-column label="Email" prop="email" />
              <el-table-column label="Product Name" prop="product_name" />
              <el-table-column label="Best Use" prop="best_use" />
              <el-table-column label="Price" prop="price_min" width="120px">
                <template slot-scope="scope">
                  ${{scope.row.price_min}} - ${{scope.row.price_max}}
                </template>
              </el-table-column>
              <el-table-column label="Age" prop="age_min" width="100px">
                <template slot-scope="scope">
                  {{scope.row.age_min}} - {{scope.row.age_max}}
                </template>
              </el-table-column>
              <el-table-column label="URL" prop="url" show-overflow-tooltip>
                <template slot-scope="scope">
                  <el-link :href="scope.row.url" target="_blank">{{scope.row.url}}</el-link>
                </template>
              </el-table-column>
              <el-table-column label="Shipping Option" prop="shipping_option" />
              <el-table-column label="创建时间" prop="create_time" width="160px"/>
            <el-table-column label="操作" fixed="right" width="120px">
              <template slot-scope="scope">
                <el-button type="text" @click="onEdit(scope.row)">编辑</el-button>
                <el-button type="text" style="color: #F82222" @click="onDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
      <div class="page-box">
        <el-pagination
            background
            :current-page="pageNo"
            :page-sizes="pageSizes"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalSize"
            @size-change="changePageSize"
            @current-change="changePageNo"
        />
      </div>
    </div>


    <Add ref="addFormRef" @get-page="initData" />

    <el-dialog
        top="10vh"
        width="1200px"
        title="重复数据"
        :visible.sync="repeatDialog"
        :close-on-click-modal="false"
        append-to-body
    >
      <el-table
          size="large"
          stripe
          border
          max-height="500px"
          :data="repeatData"
          row-key="id"
      >
        <el-table-column label="Email" prop="email" />
        <el-table-column label="Product Name" prop="product_name" />
        <el-table-column label="Best Use" prop="best_use" />
        <el-table-column label="Price" prop="price_min">
          <template slot-scope="scope">
            ${{scope.row.price_min}} - ${{scope.row.price_max}}
          </template>
        </el-table-column>
        <el-table-column label="Age" prop="age_min">
          <template slot-scope="scope">
            {{scope.row.age_min}} - {{scope.row.age_max}}
          </template>
        </el-table-column>
        <el-table-column label="URL" prop="url" width="200px">
          <template slot-scope="scope">
            <el-link :href="scope.row.url" target="_blank">{{scope.row.url}}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="Shipping Option" prop="shipping_option" />
      </el-table>
    </el-dialog>
    <el-dialog
        top="10vh"
        width="750px"
        title="错误数据"
        :visible.sync="errorDialog"
        :close-on-click-modal="false"
        append-to-body
    >
      <el-table
          size="large"
          stripe
          border
          max-height="500px"
          :data="errorData"
          row-key="id"
      >
        <el-table-column label="错误行" prop="index" />
        <el-table-column label="错误数据" prop="value" />
        <el-table-column label="描述" prop="desc" />
      </el-table>
    </el-dialog>
  </div>

</template>
<script>
import * as XLSX from 'xlsx';
import crud from "@/mixins/crud";
import { http } from "@/api";
import Add from "./add";
export default {
  name: "index",
  components: {
    Add
  },
  mixins: [crud],
  data() {
    return {
      request:http.product,
      searchList: [
        {
          label: 'Email',
          key: 'email',
          name: 'input',
          clearable: true
        },
        {
          label: 'Product Name',
          key: 'product_name',
          name: 'input',
          clearable: true
        }
      ],
      searchParams: {
        username: '',
        nickname: ''
      },
      tableData: [

      ],
      tableHeaders: [], // 表格头部
      repeatData: [],
      repeatDialog: false,
      errorData: [],
      errorDialog: false
    }
  },
  methods: {
    handleChange(file) {
      if (!file) return;

      const reader = new FileReader();
      let tableHeaders  = []
      let tableData = []
      reader.onload = (e) => {
        try {
          const data = e.target.result;
          const workbook = XLSX.read(data, { type: 'array' });
          const firstSheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[firstSheetName];
          const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

          // 数据库字段映射
          const dbFields = [
            'email', 'product_name', 'best_use', 'price_min', 'price_max',
            'age_min', 'age_max','shipping_option', 'url',
          ];

          if (jsonData.length > 0) {
            tableHeaders = dbFields;
            tableData = jsonData.slice(1).map(row => {
              const rowData = {};
              dbFields.forEach((field, index) => {
                rowData[field] = row[index];
              });
              return rowData;
            });
          }
          console.log(tableData)
          /**
           * 校验合法性
           * 邮箱
           * url
           */
          let errList = []
          tableData.forEach((item, index) => {
           // 正则判断邮箱
            let emailReg = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/
            if (!emailReg.test(item.email)) {
              errList.push({
                index: index + 2,
                desc: '邮箱格式错误',
                value: item.email
              })
            }
            // 链接只要是http开头就行
            let urlReg = /^http/
            if (!urlReg.test(item.url)) {
              errList.push({
                index: index + 2,
                desc: '链接格式错误',
                value: item.url
              })
            }
          });
          if (errList.length > 0) {
            this.errorData = errList
            this.errorDialog = true
            return;
          }
          this.loading = true
          http.product.createList(tableData).then(res => {
            this.loading = false
            this.initData();
            if (res.data && res.data.length) {
              this.$message.error(`导入成功${tableData.length - res.data.length}条，失败${res.data.length}条`);
            setTimeout(() => {
              this.repeatDialog = true
              this.repeatData = res.data
            },800)
              // 导入成功多少条，失败多少条
            } else {
              this.$message.success('导入成功');
            }
          }).catch(err => {
            this.loading = false
          })
        } catch (error) {
          console.error('Excel解析错误:', error);
          this.$message.error('Excel文件解析失败');
        }
      };

      reader.readAsArrayBuffer(file.raw);
    },
  }
}
</script>

<style scoped lang="scss">

</style>
